﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge.Video;
using AxIMGCTRLLib;
using Damany.Cameras;
using Damany.Controls;
using Damany.Imaging.Common;
using Damany.Imaging.PlugIns;
using Damany.RemoteImaging.Common;
using Damany.Windows.Form;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using DevComponents.DotNetBar;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using MiscUtil;
using RemoteImaging.Controls;
using RemoteImaging.Core;
using System.Threading;
using RemoteImaging.ImportPersonCompare;
using RemoteImaging.LicensePlate;
using RemoteImaging.Query;
using Damany.PC.Domain;
using RemoteImaging.YunTai;
using Frame = Damany.Imaging.Common.Frame;
using Portrait = Damany.Imaging.Common.Portrait;
using System.Linq;
using Damany.Imaging.Processors;
using DevExpress.Xpo;
using DevExpress.XtraBars.Helpers;
using IrisMode = Damany.Component.IrisMode;
using ShutterMode = Damany.Component.ShutterMode;

namespace RemoteImaging.RealtimeDisplay
{
    public partial class MainForm : DevExpress.XtraEditors.XtraForm,
        IImageScreen,
        LicensePlate.ILicensePlateObserver,
        YunTai.INavigationScreen
    {

        private int _countMaxTime = 0;
        private int _countWaitTime = 0;
        private readonly Func<CarBlacklistImporter> _carBlacklistImporterFactory;
        private readonly IAppState _appState;
        private readonly PortraitFinder _portraitFinder;
        private SplashForm splash = new SplashForm();
        private CameraInfo CurrentCamera = null;
        private BindingList<LicensePlateInfo> _licensePlates = new BindingList<LicensePlateInfo>();
        private BindingList<LicensePlateInfo> _yellowPlates = new BindingList<LicensePlateInfo>();
        private BindingList<LicensePlateInfo> _wrongDirectionPlates = new BindingList<LicensePlateInfo>();
        private const string TagName = "tag";
        private const string toolBarLayoutFile = "toolbar.xml";

        private Damany.Cameras.FoKoShVideoSourceAdapter _aironixCamera;

        private IEventAggregator _eventAggregator;
        public IEventAggregator EventAggregator
        {
            get { return _eventAggregator; }
            set
            {
                _eventAggregator = value;
                if (_eventAggregator != null)
                {
                    _eventAggregator.PortraitFound += (o, e) => this.HandlePortrait(e.Value);
                }
            }
        }

        public MainForm()
        {
            //splash.TopMost = false;
            //splash.Show();
            //splash.Update();

            InitializeComponent();

            this.Text = Properties.Settings.Default.ApplicationName;

            if (!string.IsNullOrEmpty(Program.directory))
            {
                this.Text += "-[" + Program.directory + "]";
            }

            InitStatusBar();

            InitLicensePlateGrid();


            _layoutXml = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _layoutXml);

            Application.Idle += new EventHandler(Application_Idle);
        }

        private void LoadButtonStatus()
        {
            enableFaceCapture.Down = Properties.Settings.Default.EnableFaceCapture;
            enableLprRecognize.Down = Properties.Settings.Default.EnableLprRecognize;
        }

        private void SetupQueueEvent()
        {
            Messenger.Instance.FaceImageBufferChanged +=
                (sender, args) =>
                {
                    Action act = () => barEditItemFaceQueuePercent.EditValue = args.Value;
                    this.BeginInvoke(act);
                };
            Messenger.Instance.LprImageBufferChanged +=
                (sender, args) =>
                {
                    Action act = () => barEditItemLprQueuePercentage.EditValue = args.Value;
                    this.BeginInvoke(act);
                };
        }

        private void InitLicensePlateGrid()
        {
            InitLicensePlateGridColumns(licensePlatesGridView);
            InitLicensePlateGridColumns(gridViewYellowCar);
            InitLicensePlateGridColumns(gridViewWrongDir);

            licensePlatesGridView.FocusedRowChanged += licensePlatesGridView_FocusedRowChanged;
            gridViewYellowCar.FocusedRowChanged += licensePlatesGridView_FocusedRowChanged;
            gridViewWrongDir.FocusedRowChanged += licensePlatesGridView_FocusedRowChanged;

            gridViewWrongDir.RowClick += GridViewWrongDirOnRowClick;
            gridViewYellowCar.RowClick += GridViewWrongDirOnRowClick;
            licensePlatesGridView.RowClick += GridViewWrongDirOnRowClick;

            licensePlatesGrid.DataSource = _licensePlates;
            gridControlYellowLicensePlate.DataSource = _yellowPlates;
            gridControlWrongDir.DataSource = _wrongDirectionPlates;
        }

        private void GridViewWrongDirOnRowClick(object sender, RowClickEventArgs rowClickEventArgs)
        {
            ShowDetail(sender, rowClickEventArgs.RowHandle);
        }

        private IntPtr ptzHandle = IntPtr.Zero;
        private uint ptzSpeed = 1;
        private PtzControlType ptzControType;
        private void PtzControl(bool start)
        {
            uint.TryParse(textEditPtzSpeed.Text, out ptzSpeed);
            AironixControl.TMCC_PtzControl(ptzHandle, (uint)ptzControType, start ? (uint)1 : (uint)0, ptzSpeed);
        }

        private void sbZoomAdd_Click(object sender, EventArgs e)
        {
            ptzControType = PtzControlType.PTZ_ZOOM_OUT;
            PtzControl(true);
        }

        private void right_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_RIGHT;
            PtzControl(true);
        }

        private void right_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_RIGHT;
            PtzControl(false);
        }



        private void up_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_UP;
            PtzControl(true);
        }

        private void up_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_UP;
            PtzControl(false);
        }

        private void left_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_LEFT;
            PtzControl(false);
        }

        private void left_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_LEFT;
            PtzControl(true);
        }

        private void down_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_DOWN;
            PtzControl(true);
        }

        private void down_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_DOWN;
            PtzControl(false);
        }

        private void sbZoomAdd_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_ZOOM_IN;
            PtzControl(true);
        }

        private void sbZoomAdd_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_ZOOM_IN;
            PtzControl(false);
        }

        private void sbZoomSub_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_ZOOM_OUT;
            PtzControl(true);
        }

        private void sbZoomSub_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_ZOOM_OUT;
            PtzControl(false);
        }

        private void sbIRISAdd_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_IRIS_ENLARGE;
            PtzControl(false);
        }

        private void sbIRISAdd_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_IRIS_ENLARGE;
            PtzControl(true);
        }

        private void sbIRISSub_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_IRIS_SHRINK;
            PtzControl(true);
        }

        private void sbIRISSub_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_IRIS_SHRINK;
            PtzControl(false);
        }

        private void sbFOCUSAdd_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_FOCUS_FAR;
            PtzControl(false);
        }

        private void sbFOCUSAdd_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_FOCUS_FAR;
            PtzControl(true);
        }

        private void sbFOCUSSub_MouseDown(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_FOCUS_NEAR;
            PtzControl(true);
        }

        private void sbFOCUSSub_MouseUp(object sender, MouseEventArgs e)
        {
            ptzControType = PtzControlType.PTZ_FOCUS_NEAR;
            PtzControl(true);
        }

        private void sbCallGlobalCameraPosition_Click(object sender, EventArgs e)
        {
            ptzControType = PtzControlType.PTZ_SET_PRESET;
            int positionIndex = 99;
            bool isConcertSuccessful = int.TryParse(cbePreset.Text, out positionIndex);
            if (!isConcertSuccessful)
            {
                positionIndex = 99;
            }
            for (uint i = 0; i < 16; i++)
            {
                int ret = AironixControl.TMCC_PtzPreset(ptzHandle, (uint)ptzControType, i + 1, ptzSpeed);
            }

        }
        private void sbSaveGlobalCameraPosition_Click(object sender, EventArgs e)
        {
            ptzControType = PtzControlType.PTZ_SET_PRESET;
            int positionIndex = 99;
            bool isConcertSuccessful = int.TryParse(cbePreset.Text, out positionIndex);
            if (!isConcertSuccessful)
            {
                positionIndex = 99;
            }
            int ret = AironixControl.TMCC_PtzPreset(ptzHandle, (uint)ptzControType, (uint)positionIndex, ptzSpeed);
        }
        private void goToPreset_Click(object sender, EventArgs e)
        {
            ptzControType = PtzControlType.PTZ_GOTO_PRESET;
            int positionIndex = 99;
            bool isConcertSuccessful = int.TryParse(cbePreset.Text, out positionIndex);
            if (!isConcertSuccessful)
            {
                positionIndex = 99;
            }
            int ret = AironixControl.TMCC_PtzPreset(ptzHandle, (uint)ptzControType, (uint)positionIndex, ptzSpeed);
        }

        private void sbDeleteGlobalCameraPosition_Click(object sender, EventArgs e)
        {
            ptzControType = PtzControlType.PTZ_CLE_PRESET;
            int positionIndex = 99;
            bool isConcertSuccessful = int.TryParse(cbePreset.Text, out positionIndex);
            if (!isConcertSuccessful)
            {
                positionIndex = 99;
            }
            int ret = AironixControl.TMCC_PtzPreset(ptzHandle, (uint)ptzControType, (uint)positionIndex, ptzSpeed);
        }


        void center_Click(object sender, EventArgs e)
        {
            //_navController.NavStop();
            _navController.NavReturnDefultPos();

        }
        #region yuntai event
        void btnReturnDefaultPos_Click(object sender, EventArgs e)
        {
            _navController.NavReturnDefultPos();

        }

        void btnDefaultPos_Click(object sender, EventArgs e)
        {
            _navController.NavDefultPos();
        }

        void btnCWipers_MouseUp(object sender, MouseEventArgs e)
        {
            _navController.NavStop();
        }

        void btnCWipers_MouseDown(object sender, MouseEventArgs e)
        {
            if (SelectedCamera() == null)
            {
                MessageBox.Show("请先选择一个摄像头", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            _navController.NavCameraSwitchOff();
        }

        void btnCHighlghts_MouseUp(object sender, MouseEventArgs e)
        {
            _navController.NavStop();
        }

        void btnCHighlghts_MouseDown(object sender, MouseEventArgs e)
        {
            if (SelectedCamera() == null)
            {
                MessageBox.Show("请先选择一个摄像头", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            _navController.NavCameraZoomTele();

        }

        void btnCFocus_MouseUp(object sender, MouseEventArgs e)
        {
            _navController.NavStop();
        }

        void btnCFocus_MouseDown(object sender, MouseEventArgs e)
        {
            if (SelectedCamera() == null)
            {
                MessageBox.Show("请先选择一个摄像头", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            _navController.NavCameraFocusOut();
        }

        void btnCAperture_MouseUp(object sender, MouseEventArgs e)
        {
            _navController.NavStop();
        }

        void btnCAperture_MouseDown(object sender, MouseEventArgs e)
        {
            if (SelectedCamera() == null)
            {
                MessageBox.Show("请先选择一个摄像头", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            _navController.NavCameraIrisClose();
        }

        void btnAWipers_MouseUp(object sender, MouseEventArgs e)
        {
            _navController.NavStop();
        }

        void btnAWipers_MouseDown(object sender, MouseEventArgs e)
        {
            if (SelectedCamera() == null)
            {
                MessageBox.Show("请先选择一个摄像头", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            _navController.NavCameraSwitchOn();
        }

        void btnAHighlghts_MouseUp(object sender, MouseEventArgs e)
        {
            _navController.NavStop();
        }

        void btnAHighlghts_MouseDown(object sender, MouseEventArgs e)
        {
            if (SelectedCamera() == null)
            {
                MessageBox.Show("请先选择一个摄像头", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            _navController.NavCameraZoomWide();
        }

        void btnAFocus_MouseUp(object sender, MouseEventArgs e)
        {
            _navController.NavStop();
        }

        void btnAFocus_MouseDown(object sender, MouseEventArgs e)
        {
            if (SelectedCamera() == null)
            {
                MessageBox.Show("请先选择一个摄像头", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            _navController.NavCameraFocusIn();
        }

        void btnAAperture_MouseUp(object sender, MouseEventArgs e)
        {
            _navController.NavStop();
        }

        void btnAAperture_MouseDown(object sender, MouseEventArgs e)
        {

            if (SelectedCamera() == null)
            {
                MessageBox.Show("请先选择一个摄像头", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            _navController.NavCameraIrisOpen();
        }

        void ReturnDefultPos_Click(object sender, EventArgs e)
        {
            if (SelectedCamera() == null)
            {
                MessageBox.Show("请先选择一个摄像头", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            _navController.NavReturnDefultPos();
        }
        void StartMaxTimer()
        {
            _countMaxTime = 0;
            tmMaxTime.Enabled = true;
            tmWait.Enabled = false;
            _countWaitTime = 0;
        }
        void StartWaitTimer()
        {
            _countWaitTime = 0;
            tmWait.Enabled = true;

        }

        #endregion

        public MainForm(Func<IPicQueryPresenter> picQueryPresenterCreator,
                        Func<IVideoQueryPresenter> createVideoQueryPresenter,
                        Func<OptionsForm> createOptionsForm,
                        Func<OptionsPresenter> createOptionsPresenter,
                        Func<FormSuspectCarManager> formSuspectCarManagerFactory,
                        Func<FormSuspectCarQuery> formSuspectCarQueryFactory,
                        Func<ILicensePlateSearchPresenter> licensePlateSearchFactory,
                        ILicenseplateRecognizerController lprController,
                        ILicenseplateProvider licenseplateProvider,
                        IMessageBoxService messageBoxService,
                        IVideoSource videoSource,
                        ConfigurationManager configurationManager,
                        FileSystemStorage videoRepository,
                        Func<CarBlacklistImporter> carBlacklistImporterFactory,
                        IAppState appState,
            PortraitFinder portraitFinder
                        )
            : this()
        {
            _carBlacklistImporterFactory = carBlacklistImporterFactory;
            _appState = appState;
            _portraitFinder = portraitFinder;
            if (formSuspectCarQueryFactory == null) throw new ArgumentNullException("formSuspectCarQueryFactory");
            if (lprController == null) throw new ArgumentNullException("lprController");
            if (licenseplateProvider == null) throw new ArgumentNullException("licenseplateProvider");
            if (messageBoxService == null) throw new ArgumentNullException("messageBoxService");
            if (videoSource == null) throw new ArgumentNullException("videoSource");

            this.picPresenterCreator = picQueryPresenterCreator;
            _createVideoQueryPresenter = createVideoQueryPresenter;
            this._createOptionsPresenter = createOptionsPresenter;
            _formSuspectCarManagerFactory = formSuspectCarManagerFactory;
            _formSuspectCarQueryFactory = formSuspectCarQueryFactory;
            _licensePlateSearchFactory = licensePlateSearchFactory;
            _lprController = lprController;
            _licenseplateProvider = licenseplateProvider;
            _messageBoxService = messageBoxService;
            _videoSource = videoSource;
            _configurationManager = configurationManager;
            this._createOptionsForm = createOptionsForm;
            _videoRepository = videoRepository;

            configurationManager.ConfigurationChanged += configurationManager_ConfigurationChanged;

        }

        void configurationManager_ConfigurationChanged(object sender, EventArgs e)
        {
            this.Cameras = Damany.RemoteImaging.Common.ConfigurationManager.GetDefault().GetCameras().ToArray();
        }

        public LicensePlate.ILicensePlateEventPublisher LicensePlateEventPublisher
        {
            set
            {
                _licensePlateEventPublisher = value;
                _licensePlateEventPublisher.RegisterForLicensePlateEvent(this);
            }
        }

        public void ShowMessage(string msg)
        {
            if (InvokeRequired)
            {
                Action<string> action = this.ShowMessage;
                this.BeginInvoke(action, msg);
                return;
            }

            MessageBox.Show(msg, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public void AttachController(MainController controller)
        {
            this.controller = controller;
        }

        void Application_Idle(object sender, EventArgs e)
        {
            if (this.splash != null)
            {
                this.splash.Dispose();
            }
        }




        private TreeNode getTopCamera(TreeNode node)
        {
            if (node.Parent == null) return node;

            while (node.Tag == null || !(node.Tag is CameraInfo))
            {
                node = node.Parent;
            }
            return node;
        }


        #region IImageScreen Members

        public CameraInfo GetSelectedCamera()
        {
            return CurrentCamera;
        }


        private CapturedObject _selectedObject;
        public CapturedObject SelectedObject
        {
            get { return _selectedObject; }

        }

        public Frame BigImage
        {
            set
            {
                if (InvokeRequired)
                {
                    Action action = delegate
                                        {
                                            this.BigImage = value;
                                        };
                    this.BeginInvoke(action);
                    return;
                }

                this.bigImage.Picture = value.GetImage().ToBitmap();
                this.bigImage.Tag = value;

            }
        }

        public IImageScreenObserver Observer { get; set; }

        private void ShowLiveFace(ImageDetail[] images)
        {
            if (images.Length == 0) return;

            this.bigImage.Picture = (Bitmap)Damany.Util.Extensions.MiscHelper.FromFileBuffered(images.Last().Path);
        }


        public void ShowImages(ImageDetail[] images)
        {
            ImageCell[] cells = new ImageCell[images.Length];
            for (int i = 0; i < cells.Length; i++)
            {
                Image img = Damany.Util.Extensions.MiscHelper.FromFileBuffered(images[i].Path);
                string text = images[i].CaptureTime.ToString();
                ImageCell newCell = new ImageCell() { Image = img, Path = images[i].Path, Text = text, Tag = null };
                cells[i] = newCell;
            }

            ShowLiveFace(images);

            this.squareListView1.ShowImages(cells);

        }

        #endregion


        private CameraInfo GetLastSelectedCamera()
        {
            int lastId = Properties.Settings.Default.LastSelCamID;
            return Damany.RemoteImaging.Common.ConfigurationManager.GetDefault().GetCameraById(lastId);
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            UpdateClosedWindowMenu();
            this.controller.Start();
            LoadButtonStatus();
        }

        #region IImageScreen Members

        public CameraInfo[] Cameras
        {
            set
            {
                if (value == null)
                {
                    return;
                }

                if (value.Length == 0)
                {
                    return;

                }

                this.CurrentCamera = value[0];
            }
        }

        #endregion


        private void squareListView1_SelectedCellChanged(object sender, EventArgs e)
        {
            if (this.squareListView1.SelectedCell == null) return;

            var portrait = this.squareListView1.SelectedCell.Tag as Portrait;
            if (portrait == null) return;

            this.BigImage = portrait.Frame.Clone();
            currLicenseNumber.EditValue = null;
            currLicenseCaptureTime.EditValue = portrait.CapturedAt;

            _selectedObject = portrait;
        }



        private void ShowSearchPicture()
        {
            var p = this.picPresenterCreator();
            p.Start();
        }


        /// Return Type: BOOL->int
        ///hWnd: HWND->HWND__*
        [DllImport("user32.dll", EntryPoint = "BringWindowToTop")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool BringWindowToTop([In()] IntPtr hWnd);

        /// Return Type: BOOL->int
        ///hWnd: HWND->HWND__*
        ///nCmdShow: int
        [DllImport("user32.dll", EntryPoint = "ShowWindow")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ShowWindow([In()] IntPtr hWnd, int nCmdShow);

        System.Diagnostics.Process videoDnTool;

        private void dnloadVideo_Click(object sender, EventArgs e)
        {
            if (videoDnTool != null && !videoDnTool.HasExited)
            {
                //restore window and bring it to top
                ShowWindow(videoDnTool.MainWindowHandle, 9);
                BringWindowToTop(videoDnTool.MainWindowHandle);
                return;
            }

            videoDnTool = System.Diagnostics.Process.Start(Properties.Settings.Default.VideoDnTool);
            videoDnTool.EnableRaisingEvents = true;
            videoDnTool.Exited += videoDnTool_Exited;

        }

        void videoDnTool_Exited(object sender, EventArgs e)
        {
            videoDnTool = null;
        }


        private void ShowSearchVideoForm()
        {
            var p = _createVideoQueryPresenter();
            p.Start();
        }

        Thread thread = null;
        string tempComName = "";
        int tempModel = 0;

        private void ShowOptionsForm()
        {
            var p = this._createOptionsPresenter();
            p.Start();
        }

        private void column1by1_Click(object sender, EventArgs e)
        {
            this.squareListView1.NumberOfColumns = 1;
        }

        private void column2by2_Click(object sender, EventArgs e)
        {
            this.squareListView1.NumberOfColumns = 2;
        }

        private void column3by3_Click(object sender, EventArgs e)
        {
            this.squareListView1.NumberOfColumns = 3;
        }

        private void column4by4_Click(object sender, EventArgs e)
        {
            this.squareListView1.NumberOfColumns = 4;
        }

        private void column5by5_Click(object sender, EventArgs e)
        {
            this.squareListView1.NumberOfColumns = 5;
        }

        private void InitStatusBar()
        {
        }

        private void aboutButton_Click(object sender, EventArgs e)
        {
            AboutBox about = new AboutBox();
            about.ShowDialog();
            about.Dispose();
        }

        long lastFreeSpaceBytes;


        private void statusOutputFolder_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@"explorer.exe",
                Properties.Settings.Default.OutputPath);
        }

        private void statusUploadFolder_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@"explorer.exe",
               Properties.Settings.Default.ImageUploadPool);
        }

        private void cameraTree_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {

        }


        #region IImageScreen Members


        public bool ShowProgress
        {
            set
            {

            }
        }

        public void StepProgress()
        {


        }

        #endregion

        PerformanceCounter cpuCounter;
        PerformanceCounter ramCounter;

        private string getCurrentCpuUsage()
        {
            return String.Format("{0:F0}%", cpuCounter.NextValue());
        }

        private string getAvailableRAM()
        {
            return String.Format("{0}MB", ramCounter.NextValue());
        }

        private void ShowDetailPic(ImageDetail img)
        {
        }

        private void pictureEdit1_DoubleClick(object sender, EventArgs e)
        {
            //if (this.pictureEdit1.Tag == null)
            //{
            //    return;
            //}

            //ImageDetail img = this.pictureEdit1.Tag as ImageDetail;

            //ShowDetailPic(img);

        }

        private void ShowPic()
        {
            if (this.squareListView1.SelectedCell == null)
                return;
            string p = this.squareListView1.SelectedCell.Path;
            if (p == null) return;

            this.ShowDetailPic(ImageDetail.FromPath(p));
        }


        private void squareListView1_CellDoubleClick(object sender, CellDoubleClickEventArgs args)
        {
            ShowPic();
        }




        private void playRelateVideo_Click(object sender, EventArgs e)
        {
            controller.PlayVideo();
        }


        string videoPlayerPath;

        public void StartRecord(CameraInfo cam)
        {

            if (InvokeRequired)
            {
                Action<CameraInfo, AxIMGCTRLLib.AxCamImgCtrl> action = StartRecordInternal;

                this.BeginInvoke(action, cam, _sanyoViewer);
                return;
            }

            StartRecordInternal(cam, _sanyoViewer);
        }

        private void StartRecordInternal(CameraInfo cam, AxIMGCTRLLib.AxCamImgCtrl axCamImgCtrl)
        {
            _sanyoViewer.CamImgCtrlStop();


            _sanyoViewer.ImageFileURL = @"liveimg.cgi";
            _sanyoViewer.ImageType = @"MPEG";
            _sanyoViewer.CameraModel = 1;
            _sanyoViewer.CtlLocation = @"http://" + cam.Location.Host;
            _sanyoViewer.uid = "guest";
            _sanyoViewer.pwd = "guest";
            _sanyoViewer.RecordingFolderPath
                = Path.Combine(Util.GetVideoOutputPath(), cam.Id.ToString("D2"));
            _sanyoViewer.RecordingFormat = 0;
            _sanyoViewer.UniIP = axCamImgCtrl.CtlLocation;
            _sanyoViewer.UnicastPort = 3939;
            _sanyoViewer.ComType = 0;

            if (Properties.Settings.Default.Live)
            {
                _sanyoViewer.CamImgCtrlStart();
                _sanyoViewer.CamImgRecStart();
            }
        }

        private void OnConnectionFinished(object ex)
        {


        }


        int? lastSelCamID = null;

        private void cameraTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Parent != null)
            {
                CurrentCamera = e.Node.Tag as CameraInfo;
                _navController.CurrentCamera = CurrentCamera;
                //  MessageBox.Show(CurrentCamera.Location.ToString() + " " + CurrentCamera.Name);
            }


        }

        private void axCamImgCtrl1_InfoChanged(object sender, AxIMGCTRLLib._ICamImgCtrlEvents_InfoChangedEvent e)
        {
            Debug.WriteLine("========info changed" + e.infoConn.AlarmInfo);
        }

        private void enhanceImg_Click(object sender, EventArgs e)
        {
            this.ShowPic();
        }

        private void CenterLiveControl()
        {
            //if (_aironixCamera != null)
            //{
            //    var w = _aironixCamera.Camera.ImageWidth;
            //    var h = _aironixCamera.Camera.ImageHeight;
            //    Size size = new Size(w, h);
            //    float num = Math.Min((float)(((float)aonixLiveViewer.ClientRectangle.Width) / ((float)size.Width)), (float)(((float)aonixLiveViewer.ClientRectangle.Height) / ((float)size.Height)));
            //    var rectangle = new Rectangle();
            //    rectangle.Width = (int)(size.Width * num);
            //    rectangle.Height = (int)(size.Height * num);
            //    rectangle.X = (aonixLiveViewer.ClientRectangle.Width - rectangle.Width) / 2;
            //    rectangle.Y = (aonixLiveViewer.ClientRectangle.Height - rectangle.Height) / 2;

            //    _aironixCamera.Camera.DisplayPos = aonixLiveViewer.ClientRectangle;
            //}

        }
        private void panelControl1_SizeChanged(object sender, EventArgs e)
        {
            CenterLiveControl();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            LoadLocalization();

            SkinHelper.InitSkinPopupMenu(skinsLink);

            if (File.Exists(_layoutXml))
            {
                try
                {
                    dockManager1.RestoreFromXml(_layoutXml);
                }
                catch { }
            }

            if (File.Exists(toolBarLayoutFile))
            {
                try
                {
                    barManager1.RestoreFromXml(toolBarLayoutFile);
                }
                catch (Exception)
                {

                }
            }

            this.switchMode.EditValue = Properties.Settings.Default.WorkingMode;

            CreateCameraLiveViewer();

            InitializeCameraControl();

            CenterLiveControl();

            SetupQueueEvent();

            _videoSource.NewFrame += (o, args) =>
                                         {
                                             if (liveImageTab.Visible)
                                             {
                                                 var old = canvasUserControl1.BackgroundImage;
                                                 var newImg = AForge.Imaging.Image.Clone(args.Frame);
                                                 canvasUserControl1.BackgroundImage = newImg;
                                                 if (old != null)
                                                 {
                                                     old.Dispose();
                                                 }

                                             }

                                         };

            canvasUserControl1.ArrowDrawn +=
                    (o, args) =>
                    {
                        var l = canvasUserControl1.Arrow;
                        var pt = new Point(l.End.X - l.Start.X, l.End.Y - l.Start.Y);
                        _licenseplateProvider.ReverseDirection = pt;
                    };

            canvasUserControl1.RectangleDrawn += (o, args) =>
                                                     {
                                                         var roi = canvasUserControl1.Roi;
                                                         _licenseplateProvider.Roi = roi;
                                                         _portraitFinder.ROI = roi;
                                                         Properties.Settings.Default.FaceSearchROI = roi;
                                                         Properties.Settings.Default.Save();
                                                     };

            //this.TopMost = true;
            //this.FormBorderStyle = FormBorderStyle.None;
            //this.WindowState = FormWindowState.Maximized;
            //this.Bounds = Screen.PrimaryScreen.Bounds;
        }

        private void InitializeCameraControl()
        {
            var cameraInfo = ConfigurationManager.GetDefault().GetCameras().FirstOrDefault();
            if (cameraInfo != null)
            {
                if (cameraInfo.Provider == CameraProvider.AipStar)
                {
                    this.aonixLiveViewer = new Controls.AironixLiveViewer();

                    aonixLiveViewer.Dock = DockStyle.Fill;
                    this.liveVideoTab.Controls.Add(aonixLiveViewer);

                    _aironixCamera = new FoKoShVideoSourceAdapter(aonixLiveViewer.Handle);
                    _aironixCamera.Camera.UserName = cameraInfo.LoginUserName ?? "system";
                    _aironixCamera.Camera.Password = cameraInfo.LoginPassword ?? "system";
                    _aironixCamera.Camera.Ip = cameraInfo.Location.Host.ToString();
                    _aironixCamera.Camera.Port = 6002;
                    _aironixCamera.FrameInterval = cameraInfo.Interval;
                    _aironixCamera.Camera.StreamId = 0;

                    _aironixCamera.Start();

                    _aironixCamera.Camera.PathFunc = d =>
                    {
                        var universalTime = d.ToUniversalTime();
                        var root = Util.GetVideoOutputPath();
                        var relativePath =
                            string.Format(
                                "{0:d2}//NORMAL//{1:d4}{2:d2}{3:d2}//{4:d2}//{5:d2}.m4v",
                                cameraInfo.Id,
                                universalTime.Year,
                                universalTime.Month,
                                universalTime.Day,
                                universalTime.Hour,
                                universalTime.Minute);

                        var path = Path.Combine(root, relativePath);
                        var dir = Path.GetDirectoryName(path);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        return path;
                    };

                    _aironixCamera.Camera.StartRecord();

                }
                else if (cameraInfo.Provider == CameraProvider.Sanyo)
                {
                    _sanyoViewer = new AxCamImgCtrl();
                    _sanyoViewer.Dock = DockStyle.Fill;
                    _sanyoViewer.Resize += (s, e) =>
                                           _sanyoViewer.SetWindowSize(0, 0, _sanyoViewer.ClientRectangle.Width,
                                                                      _sanyoViewer.ClientRectangle.Height, 0);
                    mainPanel.Controls.Add(_sanyoViewer);

                    StartRecord(cameraInfo);
                }
                else if (cameraInfo.Provider == CameraProvider.CyNet)
                {
                    var pictureBox = new PictureBox();
                    pictureBox.Dock = DockStyle.Fill;
                    pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
                    liveVideoTab.Controls.Add(pictureBox);
                    if (_videoSource != null)
                    {
                        _videoSource.NewFrame += (sender, args) =>
                                                     {
                                                         var pic = AForge.Imaging.Image.Clone(args.Frame);
                                                         Action<Image> showpic = i =>
                                                                              {
                                                                                  var old = pictureBox.Image;
                                                                                  pictureBox.Image = i;
                                                                                  if (old != null)
                                                                                  {
                                                                                      old.Dispose();
                                                                                  }
                                                                              };
                                                         pictureBox.BeginInvoke(showpic, pic);

                                                     };
                    }
                }


            }
        }

        private void CreateCameraLiveViewer()
        {
        }

        private static void LoadLocalization()
        {
            //DevExpress.Accessibility.AccLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressUtilsLocalizationCHS();
            //DevExpress.XtraBars.Localization.BarLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraBarsLocalizationCHS();
            //DevExpress.XtraCharts.Localization.ChartLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraChartsLocalizationCHS();
            //DevExpress.XtraEditors.Controls.Localizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraEditorsLocalizationCHS();
            //DevExpress.XtraGrid.Localization.GridLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraGridLocalizationCHS();
            //DevExpress.XtraLayout.Localization.LayoutLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraLayoutLocalizationCHS();
            //DevExpress.XtraNavBar.NavBarLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraNavBarLocalizationCHS();
            ////DevExpress.XtraPivotGrid.Localization.PivotGridLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraPivotGridLocalizationCHS();
            //DevExpress.XtraPrinting.Localization.PreviewLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraPrintingLocalizationCHS();
            ////DevExpress.XtraReports.Localization.ReportLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraReportsLocalizationCHS();
            //DevExpress.XtraRichEdit.Localization.XtraRichEditLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraRichEditLocalizationCHS();
            //// DevExpress.XtraRichEdit.Localization.RichEditExtensionsLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraRichEditExtensionsLocalizationCHS();
            ////DevExpress.XtraScheduler.Localization.SchedulerLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraSchedulerLocalizationCHS();
            //// DevExpress.XtraScheduler.Localization.SchedulerExtensionsLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraSchedulerExtensionsLocalizationCHS();
            ////DevExpress.XtraSpellChecker.Localization.SpellCheckerLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraSpellCheckerLocalizationCHS();
            //DevExpress.XtraTreeList.Localization.TreeListLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraTreeListLocalizationCHS();
            //DevExpress.XtraVerticalGrid.Localization.VGridLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraVerticalGridLocalizationCHS();
        }
        void testButton_Click(object sender, EventArgs e)
        {
            _videoRepository.DeleteMostOutDatedDataForDay(0, 1);
        }

        private void tsbFileSet_Click(object sender, EventArgs e)
        {

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {

            _appState.IsExiting = true;

            controller.Stop();

            if (_aironixCamera != null)
            {
                _aironixCamera.Stop();
                _aironixCamera.Camera.StopRecord();
            }

            if (_sanyoViewer != null)
            {
                _sanyoViewer.CamImgRecStop();
                _sanyoViewer.CamImgCtrlStop();
            }

            if ((thread != null) && (thread.IsAlive))
            {
                thread.Abort();
            }

            if (lastSelCamID != null)
            {
                Properties.Settings.Default.LastSelCamID = (int)this.lastSelCamID;
            }
            try
            {
                // _navController.NavReturnDefultPos();
            }
            catch { }

            barManager1.SaveLayoutToXml(toolBarLayoutFile);

            DevExpress.Skins.Skin currentSkin = DevExpress.Skins.CommonSkins.GetSkin(DevExpress.LookAndFeel.UserLookAndFeel.Default);
            Properties.Settings.Default.SkinUsed = currentSkin.Name;

            Properties.Settings.Default.WorkingMode = (int)switchMode.EditValue;
            Debug.WriteLine(Properties.Settings.Default.WorkingMode);
            Properties.Settings.Default.Save();
            dockManager1.SaveLayoutToXml(_layoutXml);

        }

        private void tsbMonitoring_Click(object sender, EventArgs e)
        {
            Monitoring monitoring = new Monitoring();
            monitoring.ShowDialog(this);
        }

        private void SetupCameraToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void ViewCameraToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.controller.Start();
        }


        private void toolStripButton1_Click(object sender, EventArgs e)
        {

            DialogResult res = MessageBox.Show("设置背景后将影响人脸识别准确度, 你确认要设置背景吗?", "警告",
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (res != DialogResult.Yes) return;

        }


        #region IImageScreen Members


        public void ShowSuspects(Damany.Imaging.Common.PersonOfInterestDetectionResult result)
        {
            if (InvokeRequired)
            {
                Action<Damany.Imaging.Common.PersonOfInterestDetectionResult> action = this.ShowSuspects;

                this.BeginInvoke(action, result);
                return;
            }

            alertForm.AddSuspects(result);

        }


        #endregion

        private void faceRecognize_CheckedChanged(object sender, EventArgs e)
        {
        }


        public void HandlePortrait(Portrait portrait)
        {
            var clone = portrait.Clone();

            Action action = () =>
                             {
                                 var imgCells = new ImageCell()
                                                    {
                                                        Image = clone.GetIpl().ToBitmap(),
                                                        Text = clone.CapturedAt.ToShortTimeString(),
                                                        Tag = clone
                                                    };

                                 this.squareListView1.ShowImages(new[] { imgCells });
                             };

            if (InvokeRequired)
            {
                this.BeginInvoke(action);
            }
            else
            {
                action();
            }


        }

        public void Stop()
        {
        }

        public string Description
        {
            get { throw new NotImplementedException(); }
        }

        public string Author
        {
            get { throw new NotImplementedException(); }
        }

        public Version Version
        {
            get { throw new NotImplementedException(); }
        }

        public bool WantCopy
        {
            get { return true; }
        }

        public bool WantFrame
        {
            get { return false; }
        }

        //  public event EventHandler<System.EventArgs<Exception>> Stopped;

        private MainController controller;
        private Func<OptionsPresenter> _createOptionsPresenter;
        private readonly Func<FormSuspectCarManager> _formSuspectCarManagerFactory;
        private readonly Func<FormSuspectCarQuery> _formSuspectCarQueryFactory;
        private readonly Func<ILicensePlateSearchPresenter> _licensePlateSearchFactory;
        private readonly ILicenseplateRecognizerController _lprController;
        private readonly ILicenseplateProvider _licenseplateProvider;
        private readonly IMessageBoxService _messageBoxService;
        private readonly IVideoSource _videoSource;
        private readonly ConfigurationManager _configurationManager;
        private readonly FileSystemStorage _videoRepository;
        private Func<OptionsForm> _createOptionsForm;

        private void faceRecognize_Click(object sender, EventArgs e)
        {

        }

        private void faceLibBuilder_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("FaceLibraryBuilder.exe");
        }

        ImportPersonCompare.ImmediatelyModel alertForm = new ImportPersonCompare.ImmediatelyModel();

        private void alermForm_Click(object sender, EventArgs e)
        {
            this.alertForm.Show(this);
        }




        public ConfigurationSectionHandlers.ButtonsVisibleSectionHandler ButtonsVisible
        {
            set
            {

            }
        }


        private void axCamImgCtrl1_Enter(object sender, EventArgs e)
        {

        }

        private void licensePlateList_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
        {

        }

        public void LicensePlateCaptured(LicensePlateInfo licensePlateInfo)
        {
            if (InvokeRequired)
            {
                Action<LicensePlateInfo> action = LicensePlateCaptured;
                this.Invoke(action, licensePlateInfo);
                return;
            }

            var camInfo = _configurationManager.GetCameraById(licensePlateInfo.CapturedFrom);
            var cameraName = "未知摄像头";
            if (camInfo != null)
            {
                cameraName = camInfo.Name ?? "未知摄像头";
            }

            _licensePlates.Add(licensePlateInfo);
            if (licensePlateInfo.LicensePlateColor == "黄"
                && !string.IsNullOrEmpty(licensePlateInfo.LicensePlateNumber)
                && !licensePlateInfo.LicensePlateNumber.Contains("学"))
            {
                _yellowPlates.Add(licensePlateInfo);
            }
            if (licensePlateInfo.WrongDirection)
            {
                _wrongDirectionPlates.Add(licensePlateInfo);
            }

            var idx = licensePlatesGridView.GetRowHandle(_licensePlates.Count - 1);
            licensePlatesGridView.FocusedRowHandle = idx;

            if (_licensePlates.Count > Properties.Settings.Default.MaxmumLicenseplates)
            {
                _licensePlates.RemoveAt(0);
            }

            if (_yellowPlates.Count > Properties.Settings.Default.MaxmumLicenseplates)
            {
                _yellowPlates.RemoveAt(0);
            }

            if (_wrongDirectionPlates.Count > Properties.Settings.Default.MaxmumLicenseplates)
            {
                _wrongDirectionPlates.RemoveAt(0);
            }

        }

        private LicensePlate.ILicensePlateEventPublisher _licensePlateEventPublisher;

        private void searchLicensePlates_Click(object sender, EventArgs e)
        {
            var presenter = _licensePlateSearchFactory();
            presenter.Start();
        }

        public void AttachController(NavigationController controller)
        {
            if (controller == null) throw new ArgumentNullException("controller");
            _navController = controller;
        }

        public CameraInfo SelectedCamera()
        {
            return GetSelectedCamera();
        }


        private Func<RemoteImaging.IPicQueryPresenter> picPresenterCreator;
        private readonly Func<IVideoQueryPresenter> _createVideoQueryPresenter;
        private Func<RemoteImaging.IPicQueryScreen> picScreenCreator;
        private NavigationController _navController;
        private readonly string _layoutXml = "Layout.xml";


        private void showCarPic_Click(object sender, EventArgs e)
        {

        }

        private void carPicture_DoubleClick(object sender, EventArgs e)
        {

        }

        private void tmWait_Tick(object sender, EventArgs e)
        {
            _countWaitTime = _countWaitTime + 1;
            if (_countWaitTime >= ImageConfig.WaitTime)
            {
                _countWaitTime = 0;
                tmWait.Enabled = false;
                _navController.NavReturnDefultPos();

            }
        }

        private void tmMaxTime_Tick(object sender, EventArgs e)
        {
            _countMaxTime = _countMaxTime + 1;
            if (_countMaxTime >= ImageConfig.ActionTime)
            {
                _countMaxTime = 0;
                tmMaxTime.Enabled = false;
                _navController.NavStop();

            }
        }

        private void dockPanel4_Click(object sender, EventArgs e)
        {

        }

        private void dockPanel4_Container_Paint(object sender, PaintEventArgs e)
        {

        }


        private void settingsButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowOptionsForm();
        }

        private void searchPicture_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowSearchPicture();
        }

        private void searchVideo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowSearchVideoForm();
        }


        private void licensePlatesGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
                return;

            ShowDetail(sender, e.FocusedRowHandle);
        }

        private void ShowDetail(object sender, int handle)
        {
            var gv = sender as GridView;
            if (gv != null)
            {
                var licenseplate = gv.GetRow(handle) as LicensePlateInfo;
                if (licenseplate != null)
                {
                    var source = new dummyFrameSource();
                    source.Id = licenseplate.CapturedFrom;

                    _selectedObject = new CapturedObject { CapturedAt = licenseplate.CaptureTime, CapturedFrom = source };

                    Image img = null;
                    if (licenseplate.TryLoadImageCopy(out img))
                    {
                        bigImage.Picture = (Bitmap)img;
                    }

                    currLicenseNumber.EditValue = licenseplate.LicensePlateNumber;
                    currLicenseCaptureTime.EditValue = licenseplate.CaptureTime;
                }
            }
        }

        private void optionsButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.ShowOptionsForm();
        }

        private void playRelatedVideo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.controller.PlayVideo();
        }


        class dummyFrameSource : IFrameStream
        {
            public void Initialize()
            {
                throw new NotImplementedException();
            }

            public void Connect()
            {
                throw new NotImplementedException();
            }

            public void Close()
            {
                throw new NotImplementedException();
            }

            public Frame RetrieveFrame()
            {
                throw new NotImplementedException();
            }

            public int Id
            {
                get;
                set;
            }

            public string Description
            {
                get { throw new NotImplementedException(); }
            }
        }


        private bool _videoIsFull = true;
        private Control aonixLiveViewer;
        private AxIMGCTRLLib.AxCamImgCtrl _sanyoViewer;
        private bool connected;

        private void switchView_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            //_videoIsFull = !_videoIsFull;
            //this.SuspendLayout();

            //axCamImgCtrl1.CamImgCtrlStop();

            //if (_videoIsFull)
            //{
            //    axCamImgCtrl1.Parent = mainPanel;
            //    currentLicensePlateLayoutControl.Parent = dockPanelZoomPic;
            //    axCamImgCtrl1.Height = mainPanel.ClientSize.Width;
            //    axCamImgCtrl1.Width = mainPanel.ClientSize.Height;

            //    mainPanel.Text = "实时视频";
            //    dockPanelZoomPic.Text = "放大图片";

            //}
            //else
            //{
            //    axCamImgCtrl1.Parent = dockPanelZoomPic;
            //    axCamImgCtrl1.Height = dockPanelZoomPic.ClientSize.Height;
            //    axCamImgCtrl1.Width = dockPanelZoomPic.ClientSize.Width;

            //    mainPanel.Text = "放大图片";
            //    dockPanelZoomPic.Text = "实时视频";


            //    currentLicensePlateLayoutControl.Parent = mainPanel;
            //}

            //axCamImgCtrl1.CamImgCtrlStart();


            //this.ResumeLayout();

            //return;

            //_videoIsFull = !_videoIsFull;

            //axCamImgCtrl1.Dock = _videoIsFull ? DockStyle.Fill : DockStyle.None;

            //if (!_videoIsFull)
            //{
            //    axCamImgCtrl1.Width = 170;
            //    axCamImgCtrl1.Height = 120;
            //    axCamImgCtrl1.Location = new Point(0, 0);
            //}

            //liveFullImage.Dock = _videoIsFull ? DockStyle.None : DockStyle.Fill;
            //if (_videoIsFull)
            //{
            //    liveFullImage.Width = 170;
            //    liveFullImage.Height = 120;
            //    liveFullImage.Location = new Point(0, 0);
            //}

            //if (_videoIsFull)
            //{
            //    liveFullImage.BringToFront();
            //}
            //else
            //{
            //    axCamImgCtrl1.BringToFront();
            //}


        }

        private void axCamImgCtrl1_Resize(object sender, EventArgs e)
        {
            //  axCamImgCtrl1.SetWindowSize(0, 0, axCamImgCtrl1.ClientRectangle.Width, axCamImgCtrl1.ClientRectangle.Height, 0);
        }


        private void licensePlatesGrid_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var hitInfo = licensePlatesGridView.CalcHitInfo(e.Location);
            if (hitInfo.InRow)
            {
                var row = licensePlatesGridView.GetRow(hitInfo.RowHandle);
                var licenseInfo = row as LicensePlateInfo;

                var tempPath = Path.GetTempPath();
                var tempFile = "车牌号 " + licenseInfo.LicensePlateNumber + ".jpg";
                tempFile = Path.Combine(tempPath, tempFile);

                try
                {
                    licenseInfo.Image.Save(tempFile);
                    var process = Process.Start(tempFile);
                }
                catch (Exception ex)
                {
                    _messageBoxService.ShowError("打开文件时出错");
                }


            }
        }

        private void searchLicensePlate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            searchLicensePlates_Click(null, EventArgs.Empty);
        }

        private void fullScreen_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (aonixLiveViewer != null)
            {
                SwitchFullScreen();
            }


        }

        private void SwitchFullScreen()
        {
            mainPanel.Hide();
            panelContainer1.SuspendLayout();

            Properties.Settings.Default.IsFullScreen = !Properties.Settings.Default.IsFullScreen;
            dockPanelFaceList.Visible = Properties.Settings.Default.IsFullScreen;
            dockPanelZoomPic.Visible = Properties.Settings.Default.IsFullScreen;
            dockPanelCamControl.Visible = Properties.Settings.Default.IsFullScreen; dockPanelCarList.Visible = Properties.Settings.Default.IsFullScreen;

            UpdateClosedWindowMenu();
            mainPanel.Show();
            panelContainer1.ResumeLayout();
        }



        private void ChangeParentTo(Control parent)
        {
            if (aonixLiveViewer != null)
            {
                //axCamImgCtrl1.CamImgCtrlStop();
                //aonixLiveViewer.Parent = null;

                aonixLiveViewer.Width = parent.ClientSize.Width;
                aonixLiveViewer.Height = parent.ClientSize.Height;
                aonixLiveViewer.Parent = parent;
                //this.axCamImgCtrl1.CamImgCtrlStart();
            }

        }

        private void suspectCarManage_ItemClick(object sender, ItemClickEventArgs e)
        {
            var form = _formSuspectCarManagerFactory();
            //form.CarInfos = _suspectCarRepository.GetReportedCarInfos();
            var result = form.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                //_suspectCarRepository.Save(form.CarInfos, form.RemovedInfos);
            }
        }

        private void UpdateClosedWindowMenu()
        {
            barButtonItemCameraControl.Down = dockPanelCamControl.Visible;
            barButtonItemFaceList.Down = dockPanelFaceList.Visible;
            barButtonItemCarList.Down = dockPanelCarList.Visible;
            barButtonItemBigPicture.Down = dockPanelZoomPic.Visible;
        }

        private void viewsBar_Popup(object sender, EventArgs e)
        {
            UpdateClosedWindowMenu();
        }

        private void barButtonItemCameraControl_DownChanged(object sender, ItemClickEventArgs e)
        {
            var item = sender as BarButtonItem;
            dockPanelCamControl.Visible = item.Down;
        }

        private void barButtonItemBigPicture_DownChanged(object sender, ItemClickEventArgs e)
        {
            var item = sender as BarButtonItem;
            dockPanelZoomPic.Visible = item.Down;
        }

        private void barButtonItemFaceList_DownChanged(object sender, ItemClickEventArgs e)
        {
            var item = sender as BarButtonItem;
            dockPanelFaceList.Visible = item.Down;

        }

        private void barButtonItemCarList_DownChanged(object sender, ItemClickEventArgs e)
        {
            var item = sender as BarButtonItem;
            dockPanelCarList.Visible = item.Down;

        }

        private void suspectCarQuery_ItemClick(object sender, ItemClickEventArgs e)
        {
            var form = _formSuspectCarQueryFactory();
            form.ShowDialog(this);

        }

        private void setRectangleButton_ItemClick(object sender, ItemClickEventArgs e)
        {
            var path = System.IO.Path.Combine(Application.StartupPath, Properties.Settings.Default.RectangleSetterPath);
            Process.Start(path);

        }

        private void barEditItem3_EditValueChanged(object sender, EventArgs e)
        {
            _eventAggregator.PublishSwitchMotionDetectorEvent();

            var camConfig = _configurationManager.GetCameras().FirstOrDefault();
            if (camConfig == null) return;

            var modeName = ((int)switchMode.EditValue) == 0 ? "室内模式" : "室外模式";

            var modesQuery = new XPQuery<WorkModeCamSetting>(new Session());

            var selectedConfig = modesQuery.Where(cfg => cfg.ModeName == modeName).FirstOrDefault();

            if (selectedConfig == null)
            {
                return;
            }

            if (camConfig.Provider == CameraProvider.Sanyo)
            {
                var worker = Task.Factory.StartNew(() =>
                {
                    var sanyocamera = new Damany.Component.SanyoNetCamera();
                    sanyocamera.UserName = "admin";
                    sanyocamera.Password = "admin";
                    sanyocamera.IPAddress = camConfig.Location.Host;
                    sanyocamera.Connect();

                    sanyocamera.SetIris(IrisMode.Manual,
                                        selectedConfig.IrisLevel);
                    sanyocamera.SetShutter(
                        ShutterMode.Short,
                        selectedConfig.ShutterSpeed);

                    sanyocamera.SetAGCMode(true, selectedConfig.DigitalGain);

                });
                worker.ContinueWith(ant =>
                {
                    if (ant.Exception != null)
                    {
                        var error = ant.Exception;
                        _messageBoxService.ShowError("设置摄像头参数失败! 请确认摄像机已经正确连接。");
                    }
                },
                                     CancellationToken.None,
                                     TaskContinuationOptions.OnlyOnFaulted,
                                 TaskScheduler.FromCurrentSynchronizationContext());


            }


        }

        private void startLpr_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        private void UpdateStartStopVisibility(bool makeStartVisible)
        {
            enableLprRecognize.Visibility = makeStartVisible ? BarItemVisibility.Always : BarItemVisibility.Never;
            enableFaceCapture.Visibility = makeStartVisible ? BarItemVisibility.Never : BarItemVisibility.Always;
        }
        private void ShowMb(Exception err)
        {
            if (err == null)
            {
                _messageBoxService.ShowInfo("设置成功");
            }
            else
            {
                _messageBoxService.ShowError("设置失败!\r\n\r\n" + err.Message);
            }
        }

        private void stopLpr_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        private void carStatistics_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (var form = new LicensePlate.FormReport())
            {
                form.ShowDialog(this);
            }
        }

        private void barButtonItem5_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (var form = new FaceCapture.FormReport())
            {
                form.ShowDialog(this);

            }
        }

        private void exit_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Close();
        }

        private void peopleStatistics_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (var form = new FaceCapture.FormReport())
            {
                form.ShowDialog(this);
            }
        }

        private void aboutButton_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (var form = new AboutBox())
            {
                form.ShowDialog(this);
            }
        }

        private void importDelBlackList_ItemClick(object sender, ItemClickEventArgs e)
        {
            updateCarBlacklist(false);
        }

        private void importAddCarList_ItemClick(object sender, ItemClickEventArgs e)
        {
            updateCarBlacklist(true);
        }
        private void updateCarBlacklist(bool add)
        {
            var importer = _carBlacklistImporterFactory();
            importer.InputAndUpdate(add);


        }

        private void barButtonItem5_ItemClick_1(object sender, ItemClickEventArgs e)
        {
        }

        private void enableLprRecognize_DownChanged(object sender, ItemClickEventArgs e)
        {
            Properties.Settings.Default.EnableLprRecognize = enableLprRecognize.Down;
            var msg = string.Format("车牌抓拍已经{0}", enableLprRecognize.Down ? "打开" : "关闭");
            ShowToast(msg);
        }

        private void enableFaceCapture_DownChanged(object sender, ItemClickEventArgs e)
        {
            Properties.Settings.Default.EnableFaceCapture = enableFaceCapture.Down;
            var msg = string.Format("人像抓拍已经{0}", enableFaceCapture.Down ? "打开" : "关闭");
            ShowToast(msg);

        }

        private void ShowToast(string msg)
        {
            ToastNotification.Show(this, msg, eToastPosition.MiddleCenter);
        }

        private Task<bool> ConnectToCameraAsync(CameraInfo cameraInfo)
        {
            return TaskEx.Run(() =>
            {
                tmConnectInfo_t connectInfo = new tmConnectInfo_t();
                connectInfo.pIp = cameraInfo.Location.Host;
                connectInfo.iPort = 6002;
                connectInfo.dwSize = 236;
                connectInfo.iUserLevel = 5;
                connectInfo.szUser = cameraInfo.LoginUserName;
                connectInfo.szPass = cameraInfo.LoginPassword;
                connectInfo.pUserContext = "";
                var connected = AironixControl.TMCC_Connect(ptzHandle, ref connectInfo, true);
                if (connected != 0)
                {
                    return false;
                }

                var opened = AironixControl.TMCC_PtzOpen(ptzHandle, 0, false);
                return opened == 0;
            });
        }

        private async void dockPanelCamControl_VisibilityChanged(object sender, DevExpress.XtraBars.Docking.VisibilityChangedEventArgs e)
        {
            if (ptzHandle == IntPtr.Zero)
            {
                ptzHandle = AironixControl.TMCC_Init(0);
            }

            if (e.Visibility == DockVisibility.Visible)
            {
                if (!AironixControl.TMCC_IsConnect(ptzHandle))
                {
                    var caminfos = _configurationManager.GetCameras();
                    if (caminfos.Count > 0)
                    {
                        var caminfo = caminfos[0];
                        if (caminfo.Provider == CameraProvider.AipStar)
                        {
                            panelControlYuntai.Enabled = false;
                            panelControlConnectYunTai.Visible = true;
                            var conn = false;
                            while (!conn && dockPanelCamControl.Visible)
                            {
                                conn = await ConnectToCameraAsync(caminfo);
                                if (conn)
                                {
                                    panelControlYuntai.Enabled = conn;
                                    panelControlConnectYunTai.Visible = false;
                                }
                            }
                        }
                    }
                }

            }
            else
            {
                if (AironixControl.TMCC_IsConnect(ptzHandle))
                {
                    AironixControl.TMCC_DisConnect(ptzHandle);
                }

            }
        }

        private void alertControl1_BeforeFormShow(object sender, DevExpress.XtraBars.Alerter.AlertFormEventArgs e)
        {
            var loc = this.Location;
            loc.Offset((this.Width - e.AlertForm.Width) / 2, (this.Height - e.AlertForm.Height) / 2);

            e.Location = loc;
        }

        private void barButtonItemLoadSchema_ItemClick(object sender, ItemClickEventArgs e)
        {
            var dlg = new OpenFileDialog();
            dlg.Filter = "方案文件 (*.pjs)|*.pjs";

            using (dlg)
            {
                var res = dlg.ShowDialog(this);
                if (res == DialogResult.OK)
                {
                    try
                    {
                        var spec = LicensePlate.Helper.LoadSchema(dlg.FileName);
                        _licenseplateProvider.ProjectSpecifications = spec.ToList();
                        barCheckItemEnableSchema.Checked = true;

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("载入方案错误，请确保文件格式正确", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }



        private void barEditItemEnableSchema_EditValueChanged(object sender, EventArgs e)
        {
        }

        private void barCheckItem1_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            var ck = (bool)barCheckItemEnableSchema.Checked;
            _licenseplateProvider.EnableSchema = ck;

            ShowToast("方案" + (ck ? "启用" : "禁用"));

        }

        private static void InitLicensePlateGridColumns(GridView dataGridView)
        {
            // 
            // gridColumn4
            // 
            var column1 = new GridColumn();
            column1.Caption = "车牌颜色";
            column1.FieldName = "LicensePlateColor";
            column1.Name = "gridColumn4";
            column1.Visible = true;
            column1.VisibleIndex = 1;
            // 
            // gridColumn1
            // 
            var column2 = new GridColumn();
            column2.Caption = "车牌号码";
            column2.FieldName = "LicensePlateNumber";
            column2.Name = "gridColumn1";
            column2.OptionsColumn.AllowEdit = false;
            column2.Visible = true;
            column2.VisibleIndex = 0;
            // 
            // gridColumn2
            // 
            var column3 = new GridColumn();
            column3.Caption = "抓拍时间";
            column3.DisplayFormat.FormatString = "t";
            column3.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            column3.FieldName = "CaptureTime";
            column3.Name = "gridColumn2";
            column3.OptionsColumn.AllowEdit = false;
            column3.Visible = true;
            column3.VisibleIndex = 2;

            dataGridView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
            column1,
            column2,
            column3});


        }


        private Point _startPoint;
        private Point _endPoint;
        private bool _isDrawing = false;
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            _startPoint = e.Location;
            _isDrawing = true;
        }

        private void pictureBoxReverseDirection_MouseUp(object sender, MouseEventArgs e)
        {
            _endPoint = e.Location;
            _isDrawing = false;
        }

        private void pictureBoxReverseDirection_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDrawing)
            {
                _endPoint = e.Location;
                //pictureBoxReverseDirection.Refresh();
            }
        }

        private void pictureBoxReverseDirection_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawLine(Pens.Red, _startPoint, _endPoint);

        }

        private void popupControlContainer1_CloseUp(object sender, EventArgs e)
        {
            var pt = new Point(_endPoint.X - _startPoint.X, _endPoint.Y - _startPoint.Y);
            _licenseplateProvider.ReverseDirection = pt;

            var msg = string.Format("逆向行驶检测{0}", (pt == Point.Empty) ? "关闭" : "打开");
            ToastNotification.Show(this, msg);
        }

        private void popupControlContainer1_Popup(object sender, EventArgs e)
        {
            //pictureBoxReverseDirection.Invalidate();
        }

        private void barButtonItem7_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void barButtonItemMarkRoi_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void barButtonItemMarkArrow_DownChanged(object sender, ItemClickEventArgs e)
        {
            var down = barButtonItemMarkArrow.Down;
            if (down)
            {
                xtraTabControl1.SelectedTabPage = liveImageTab;
                canvasUserControl1.Mode = DrawimgMode.Arrow;
                barButtonItemMarkRoi.Enabled = false;

            }
            else
            {
                xtraTabControl1.SelectedTabPage = liveVideoTab;
                barButtonItemMarkRoi.Enabled = true;

            }
        }

        private void barButtonItemMarkRoi_DownChanged(object sender, ItemClickEventArgs e)
        {
            if (barButtonItemMarkRoi.Down)
            {
                xtraTabControl1.SelectedTabPage = liveImageTab;
                canvasUserControl1.Mode = DrawimgMode.Rectangle;
                barButtonItemMarkArrow.Enabled = false;
            }
            else
            {
                xtraTabControl1.SelectedTabPage = liveVideoTab;
                barButtonItemMarkArrow.Enabled = true;
            }
        }

        private void barEditItemZoomFactor_EditValueChanged(object sender, EventArgs e)
        {
            var zoom = barEditItemZoomFactor.EditValue;
            _licenseplateProvider.RecognizeParameters.ZoomFactor = Convert.ToSingle(zoom);
        }

        private void barButtonItemTest_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (var form = new FormTest())
            {
                form.ShowDialog(this);
            }
        }

    }
}
